<template>
  <el-dialog
    :visible.sync="show"
    width="600px"
    center
    title="用户注册"
    @close="closeEvent"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="74px">
      <el-form-item prop="avatar" label="头像">
        <img-upload v-model="form.avatar" />
      </el-form-item>

      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username" />
      </el-form-item>

      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email" />
      </el-form-item>

      <el-form-item prop="phone" label="手机">
        <el-input v-model.number="form.phone" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-form-item prop="imgcode" label="图形码">
            <el-input v-model="form.imgcode" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <img :src="codeSrc" alt="" @click="changeImgCode">
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-form-item prop="rcode" label="验证码">
            <el-input v-model.number="form.rcode" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button class="codeBtn" :disabled="codeDisable" @click="getCode">{{
            codeDisable ? `发送验证码（${codeTime})s` : '发送验证码'
          }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeEvent">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { sendsms, register } from '@/api/register'
import config from '@/../vue.config'
export default {
  data() {
    return {
      show: false,
      codeSrc: process.env.VUE_APP_BASE_API + '/captcha?type=sendsms',
      form: {
        avatar: '', //	是	string	头像地址
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        imgcode: '', // 图形验证码
        rcode: '' //	是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: '头像未上传', trigger: 'change' }], //	是	string	头像地址
        username: [{ required: true, message: '必填', trigger: 'change' }], //	是	string	用户名
        email: [
          { required: true, message: '必填', trigger: 'change' },
          {
            pattern:
              /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确邮箱',
            trigger: 'change'
          }
        ], //	是	string	邮箱
        phone: [
          { required: true, message: '必填', trigger: 'change' },
          {
            pattern:
              /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ], //	是	string	手机号
        password: [{ required: true, message: '必填', trigger: 'change' }], //	是	string	密码
        imgcode: [{ required: true, message: '必填', trigger: 'change' }], // 图形验证码
        rcode: [{ required: true, message: '必填', trigger: 'change' }] //	是	string	验证码
      },
      codeDisable: false, // 发送验证码是否可用
      codeTime: 5 // 验证码发送倒计时
    }
  },
  watch: {
    // 侦听头像是否有值
    'form.avatar'(newval, oldval) {
      if (newval) {
        this.$refs.form.clearValidate('avatar')
      }
    }
  },
  methods: {
    // 关闭弹框事件
    closeEvent() {
      // 关闭弹框
      this.show = false
      // 重置表单数据
      this.$refs.form.resetFields()
    },
    // 图形验证码切换
    changeImgCode() {
      this.codeSrc =
        process.env.VUE_APP_BASE_API +
        '/captcha?type=sendsms&time=' +
        Date.now()
    },
    // 获取验证码

    async getCode() {
      console.log(config)
      let isVertified = true
      this.$refs.form.validateField(['phone', 'imgcode'], async(err) => {
        // 通过校验
        if (err) {
          isVertified = false
        }
      })
      if (isVertified) {
        // 设置按钮不可用
        this.codeDisable = true
        // 按钮实现倒计时
        const timer = setInterval(() => {
          this.codeTime--
          if (this.codeTime === 0) {
            // 清空定时器
            clearInterval(timer)
            // 重置倒计时
            this.codeTime = 5
            // 按钮置为可用
            this.codeDisable = false
          }
        }, 1000)
        const data = {
          code: this.form.imgcode,
          phone: this.form.phone
        }
        try {
          const res = await sendsms(data)
          this.$message.success('发送验证码成功，请查收')
          console.log(res)
          this.form.rcode = res.data.captcha
        } catch (error) {
          this.$message.error(error)
        }
      }
    },
    // 提交注册
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          const res = await register(this.form)
          console.log(res)
          this.$message.success('注册成功')
          this.show = false
          // 清空表单
          this.$refs.form.resetFields()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  height: 53px;
  background: linear-gradient(90deg, #01c4fa, #1294fa);
  .el-dialog__title {
    color: #fff;
  }
}
.avatar-uploader {
  margin: 0 150px;
}
img {
  width: 100%;
}
.codeBtn {
  width: 100%;
}
</style>
